package com.qf.utils;

import com.qf.entity.User;
import javafx.scene.input.DataFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author：刘亚康
 * @Date：2020/4/12
 * @QQ：50770284
 * @Phone：18235947935
 * @Desc : 订单工具类
 **/
@Component
public class OrderUtils {
    //订单号生成规则，yyyyMMdd 用户id 4位 流水号 Redis中获取
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public String createOrderId(Integer userId){
        StringBuffer orderId=new StringBuffer();
        //时间的生成
        Date date=new Date();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
        //1:添加时间
        orderId.append(sdf.format(date));
        //2:添加用户ID
        orderId.append(getUserId(userId));
        //3:添加Redis中的流水号
        String order_serial = stringRedisTemplate.opsForValue().get("order_serial");
        if (order_serial==null||order_serial.equals("")) {
            stringRedisTemplate.opsForValue().set("order_serial","1");
        }
        Long order_serial1 = stringRedisTemplate.opsForValue().increment("order_serial");

        String orderId1 = orderId.append(order_serial1.toString()).toString();

        return orderId1;
    }

    /**
     * 给用户ID补齐0
     * @param userId
     * @return
     */
    private static String getUserId(Integer userId) {
        String tempUId=userId.toString();
        StringBuffer uid=new StringBuffer();
        if (tempUId.length()<5){
            uid.append(tempUId);
            for (int i = 0; i <(5-tempUId.length()) ; i++) {
                uid.insert(0,0);
            }
        }

        return uid.toString();
    }
}
